const express = require('express');
const router = express.Router();
const md5=require('md5')
const Account=require('../../models/Account')
const User=require('../../models/User')
const jwt=require('jsonwebtoken')
const checkToken=require('../../middlewares/checkToken')


//查询账单
router.get('/account', checkToken,async function (req, res, next) {
    try {
    // 查询所有 Account 数据
    const accounts = await Account.find();
    res.json({
      code:'0000',
      msg:'读取成功',
      data:accounts
    })
  } catch (err) {
    res.status(500).json({
      code:'1001',
      msg:'读取失败'+err.message,
      data:null
    })
  }
  }
  )

// 添加账单
router.post('/account', checkToken,async(req, res)=>{
  try {
    const data = {
      in: req.body.in || 10,
      out: req.body.out || 10
    };
    const newAccount = await Account.create(data);
    res.json({
      code:'0000',
      msg:'添加成功',
      data:newAccount
    })  
  } catch (err) {
    res.status(500).json({
      code:'1002',
      msg:'添加失败'+err.message,
      data:null
    })
  }
});

//删除账单
router.delete('/account/:id',checkToken,async(req, res)=>{
  try {
    const id=req.params.id  
    await Account.findByIdAndDelete(id)
    res.json({
      code:'0000',
      msg:'删除成功',
      data:null
    })  
  } catch (err) {
    res.status(500).json({
      code:'1003',
      msg:'删除失败'+err.message,
      data:null
    })
  }
});


//更新账单
router.patch('/account/:id',checkToken, async(req, res)=>{
  try {
    const id=req.params.id
    const data = {
      in: req.body.in || 10,
      out: req.body.out || 10
    };
    const updatedAccount = await Account.findByIdAndUpdate(id, data, { new: true });
    res.json({
      code:'0000',
      msg:'更新成功',
      data:updatedAccount
    })  
  }
  catch (err) {
    res.status(500).json({
      code:'1004',
      msg:'更新失败'+err.message,
      data:null
    })
  }
});

module.exports = router;
